package de.hsmannheim.poolraumapp;

import java.io.IOException;

import org.joda.time.DateTime;
import org.joda.time.Period;

import de.hsmannheim.poolraumapp.db.RoomSearcher;
import de.hsmannheim.poolraumapp.model.LessonBlocks;
import de.hsmannheim.poolraumapp.model.Rooms;
import de.hsmannheim.poolraumapp.model.fetcher.LessonBlockFetcher;
import de.hsmannheim.poolraumapp.model.fetcher.RoomFetcher;
import de.hsmannheim.poolraumapp.model.fetcher.RoomReservationFetchException;
import de.hsmannheim.poolraumapp.model.fetcher.RoomReservationFetcher;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class FetcherService extends Service{
	private boolean running = false;
	private FetcherThread fetcher;
	
	private static final int DELAY = 2 * 60 * 60 * 1000;
	private static final String TAG = FetcherService.class.getName();
	
	public FetcherService() { 
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	@Override
	public void onCreate() {
		super.onCreate();				
		fetcher = new FetcherThread();
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		super.onStartCommand(intent, flags, startId);
		if (!running) {
			running = true;
			fetcher.start();
		}
		return Service.START_STICKY;
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		
		running = false;
		if (fetcher != null) {
			fetcher.interrupt();
			fetcher = null;
		}
	}
	
	private class FetcherThread extends Thread {
		@Override
		public void run() {
			while (running) {
				try {
					fetch();
					Thread.sleep(DELAY);
				} catch (InterruptedException e) {
					Log.d(TAG, "Fetcher thread interrupted");
					running = false;
				} catch (IOException e) {
					Log.d(TAG, "Fetcher thread I/O error", e);
					running = false;
				} catch (RoomReservationFetchException e) {
					Log.d(TAG, "Fetcher thread couldn't fetch reservations", e);
					running = false;
				}
			}
		}
		
		private static final String URL = "http://www.informatik.hs-mannheim.de/stundenplan/cms/?msp=1";
		
		private void fetch() throws IOException, RoomReservationFetchException {			
			RoomSearcher roomSearcher = ((PoolraumApp)getApplication()).getRoomSearcher();
			
			Rooms rooms = new RoomFetcher(getAssets().open("rooms.json")).fetch();
			DateTime roomsLastModified = roomSearcher.getRoomsLastModified();
			boolean roomsUpdated = false;
			if (roomsLastModified == null || rooms.getLastModified().isAfter(roomsLastModified)) {
				roomSearcher.setRooms(rooms);
				roomsUpdated = true;
			}
			
			LessonBlocks lessonBlocks = new LessonBlockFetcher(getAssets().open("lessonBlocks.json")).fetch();
			DateTime lessonBlocksLastModified = roomSearcher.getLessonBlocksLastModified();
			boolean lessonBlocksUpdated = false;
			if (lessonBlocksLastModified == null || lessonBlocks.getLastModified().isAfter(lessonBlocksLastModified)) {
				roomSearcher.setLessonBlocks(lessonBlocks);
				lessonBlocksUpdated = true;
			}
			
			DateTime reservationsLastModified = roomSearcher.getReservationsLastModified();
			boolean reservationsUpdated = false;
			if (reservationsLastModified == null || new Period(reservationsLastModified, new DateTime()).toStandardHours().getHours() >= 24) {
				RoomReservationFetcher roomReservationFetcher = new RoomReservationFetcher(URL);
				roomSearcher.setReservations(roomReservationFetcher.fetch());
				reservationsUpdated = true;
			}
			
			if (roomsUpdated || lessonBlocksUpdated || reservationsUpdated) {
				roomSearcher.updateResults();
			}
		}
	}
}
